package com.example.register1.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.register1.Dto.LoadDto;
import com.example.register1.Dto.PageDTO;
import com.example.register1.Dto.SignOutDTO;
import com.example.register1.domin.BookIndex;
import com.example.register1.domin.Chapter;
import com.example.register1.domin.Load11;
import com.example.register1.domin.Register;
import com.example.register1.mapper.IndexMapper;
import com.example.register1.mapper.RegisterMapper;
import com.example.register1.result.Result;
import com.example.register1.service.ChapterService;
import com.example.register1.service.LoadService;
import com.example.register1.service.RegisterService;
import com.example.register1.service.StudentClassService;
import com.example.register1.result.PageResult;
import com.example.register1.vo.BooksAndNamesVO;
import com.example.register1.vo.StuClassVO;
import com.example.register1.vo.StudentVO;
import com.example.register1.vo.NamesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import java.text.SimpleDateFormat;

import static com.example.register1.service.impl.RegisterServiceImpl.milliseconds;

@RestController
@RequestMapping("/register")
@CrossOrigin(origins = "*")
public class RegisterController {
    @Autowired
    private LoadService loadservice;
    @Autowired
    private RegisterService registerService;

    @Autowired
    private StudentClassService studentClassService;
    @Autowired
    private ChapterService chapterService;

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private IndexMapper indexMapper;

    @GetMapping("/classes")
    public List<StuClassVO> studentClasses(){


        return  studentClassService.getStuClassVO();


    }



    @PostMapping("/start")
    private Result start (@RequestBody Register register){
        LambdaQueryWrapper<Register> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Register::getName,register.getName());
        lambdaQueryWrapper.eq(Register::getIsEnd,0);
        System.out.println(registerService.list(lambdaQueryWrapper));
        if(registerService.list(lambdaQueryWrapper).size()!=0){
            return Result.error("请先签退");
        }
        Date startDate = new Date(System.currentTimeMillis());
        register.setStartDate(startDate);
//        register.setName(register.getName());
        registerService.save(register);
        return  Result.success("签到成功");
    }

    @GetMapping("/names")
    private List<NamesVO> names(){
        return loadservice.names();
    }


    @GetMapping("/efficiency")
    private Result efficiency(int page, int pageSize, String idClass,String studentClass) throws ParseException {
        //新建page查询器查询Load11
        Page<Load11> pageInfo =new Page<>(page,pageSize);
        //新建LoadDto的page对象--返回
        Page<LoadDto> loadDtoPage=new Page<>();
        Page<StudentVO> studentVOPage=new Page<>();

        //新建查询器
        LambdaQueryWrapper<Load11> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //通过班级查询所有的人
        lambdaQueryWrapper.eq(Load11::getStudentClass,studentClass);
        lambdaQueryWrapper.eq(Load11::getIdClass,idClass);
        //将Load的page数据,封装到LoadDto中
        loadservice.page(pageInfo,lambdaQueryWrapper);
        studentVOPage.setSize(pageInfo.getSize());
        //studentVOPage.setTotal(pageInfo.getTotal());
        studentVOPage.setCurrent(pageInfo.getCurrent());
         //新建LoadDtos集合--用来封装到返回数据LoadDtoPage的records中
         List<LoadDto> loadDtos=new ArrayList<>();
         List<StudentVO> studentVOS=new ArrayList<>();

         //定义总人数Total
         long total=pageInfo.getTotal();

         //循环遍历班级内每一个人
        for (Load11 list : pageInfo.getRecords()) {
            //新建Register的查询器
            LambdaQueryWrapper<Register> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            //通过name，endtime，isend查询Register内的所有数据
            lambdaQueryWrapper1.eq(Register::getName,list.getName());
            //根据退签时间进行排序
            lambdaQueryWrapper1.orderByDesc(Register::getEndDate);
            lambdaQueryWrapper1.eq(Register::getIsEnd,1);
            List<Register> list1s = registerService.list(lambdaQueryWrapper1);
            //新建一个LoadDti--用来保存数据到LoadDto-list集合

            //将该人的load内的数据封装袋loaddto中
            StudentVO studentVO=new StudentVO();

            studentVO.setName(list.getName());


//            //如果在表内没数据的逻辑
            if(list1s.size()==0){
                total--;

//                studentVO.setEfficiency("0");
//
//                studentVO.setTime("0");
//
//                studentVO.setAddChapter("0");
//
//                studentVO.setChapter("还没开始学习");
//
//                studentVOS.add(studentVO);
                continue;
            }
            //封装最新章节到loaddto
//            loadDto.setAddChapter(list1s.get(0).getIdChapter());

//            String cha = String.valueOf(list1s.get(0).getIdChapter());

            //设置时间格式
            SimpleDateFormat format1=new SimpleDateFormat("HH:mm:ss");
            //初始化时间戳变量
            Long timesTamp=0l;
            //循环遍历数据，学习时间的时间戳进行相加并存到timesTamp中
            for (Register list1 : list1s) {
                //将每一条数据的string类型学习时间转换成Date类型的时间
                Date date = format1.parse(list1.getTime());
                //将时间转化成时间戳
                Long timestamp=date.getTime()+3600000*8;
                //累加到timesTamp
                timesTamp+=timestamp;
            }
            //将累积学习时间的时间戳转换成String类型
            String timeText=format1.format(timesTamp-3600000*8);
            //将累积时间保存到loaddto中

            studentVO.setTime(timeText);
            double timesTamp_ = milliseconds(studentVO);
            //进行计算效率
            //通过时间戳计算总共学习的时间
            double l = (double)timesTamp/1000/60/60;

            String time=String.format("%.1f",l);
            studentVO.setTime(time);

            //最新章节
            Integer idChapter = list1s.get(0).getIdChapter();

            List<BookIndex> allBook = indexMapper.selectAll();
            LocalDate startTime = registerMapper.selectMinDate().toLocalDate();
            LocalDate endTime = registerMapper.selectmaxDate().toLocalDate().plusDays(1);
            Integer chaps = 0;

            for (BookIndex book : allBook) {
                String stuName = studentVO.getName();
                Integer chap = indexMapper.selectMaxChapter(stuName, book, startTime, endTime);
                if(chap!=null&&chap != 0){
                    Integer count = indexMapper.selectMax(stuName,book,startTime,endTime);
                    if(count>1){
                        chaps+= chap - book.getStartId();
                    }
                }
            }

            Integer inch = 0;
            LocalDateTime firstTime = registerMapper.selectFirstDate(studentVO.getName());
            if(firstTime!=null){
                inch = registerMapper.selectIdChapter(studentVO.getName(),firstTime);
                for (int j = 0; j < allBook.size(); j++) {
                    Integer startId = allBook.get(j).getStartId();
                    Integer endId = allBook.get(j).getEndId();
                    if(inch>=startId && inch<=endId){
                        inch = inch-startId;
                        break;
                    }
                }
            }
            //用章节除以小时计算效率
            double l1 = (chaps-inch) / l;
            //将时效率保存到loaddto中
           /* DecimalFormat decimalFormat=new DecimalFormat("#,##0.00");
            String ll=decimalFormat.format(l1);*/
            studentVO.setAddChapter(String.valueOf(chaps-inch));

            String ll=String.format("%.3f",l1);

            studentVO.setEfficiency(ll);
            //新建tb_chapter查询器
            LambdaQueryWrapper<Chapter> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
            //根据章节查询
            lambdaQueryWrapper2.eq(Chapter::getIdChapter,list1s.get(0).getIdChapter());
            Chapter chapter = chapterService.getOne(lambdaQueryWrapper2);
            //将最新章节保存到loaddto中

            studentVO.setChapter(String.valueOf(chaps));
            //将本条loaddto数据存到loaddtos的list集合中
            LocalDateTime dateTime = registerMapper.selectMaxDate(studentVO.getName());
            String chapter_ = registerMapper.selectNowChapter(dateTime,studentVO.getName());
            String content = registerMapper.selectNowContent(dateTime,studentVO.getName());
            String day = registerMapper.selectNowDay(dateTime,studentVO.getName());
            studentVO.setDay(day);
            studentVO.setContent(content);
            studentVO.setChapter(chapter_);
            studentVOS.add(studentVO);
        }
        for (int i = 0; i < studentVOS.size(); i++) {
            for (int j = 0; j < studentVOS.size()-1-i; j++) {
                if(Double.parseDouble(studentVOS.get(j).getTime())<Double.parseDouble(studentVOS.get(j+1).getTime())){
                    StudentVO s1 = studentVOS.get(j);
                    StudentVO s2 = studentVOS.get(j+1);
                    studentVOS.set(j+1,s1);
                    studentVOS.set(j,s2);
                }
            }
        }

        studentVOPage.setTotal(total);
        studentVOPage.setRecords(studentVOS);
        System.out.println(loadDtos);
        System.out.println(studentVOS);
        return Result.success(studentVOPage);
    }
    @GetMapping("/books")
    public Result<BooksAndNamesVO> selectBooksAndNames(){
        BooksAndNamesVO booksAndNames = registerService.selectBooksAndNames();
        return Result.success(booksAndNames);
    }

    @GetMapping("/time")
    public Result<PageResult> selectByTime(PageDTO pageDTO){
        System.out.println(pageDTO);
        PageResult pageResult = registerService.selectByTime(pageDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/contain")
    public Result contain(@RequestBody SignOutDTO signOutDTO){
        Result result = registerService.signOut(signOutDTO.getIdChapter(),signOutDTO.getName(),signOutDTO.getBook(),signOutDTO.getChapter());
        return result;
    }



}
